﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMouseEvent>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //将空间btn_1加载到this对象中的事件过滤器中
    ui->btn_1->installEventFilter(this);
    ui->textEdit->installEventFilter(this);

    connect(ui->btn_1, &QPushButton::pressed, this, &Widget::close);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    qDebug() << "鼠标按键按下";
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    qDebug() << "鼠标按键释放";
}

//重写事件过函数
bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->btn_1)
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if(mouseEvent->button() == Qt::LeftButton)
            {
                qDebug() << "左键射击";
            }
            else if(mouseEvent->button() == Qt::RightButton)
            {
                qDebug() << "右键开镜";
            }
            return true;
        }
    }
    else if(watched == ui->textEdit)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
            ui->textEdit->append(QString::number(keyEvent->key()));
            return true;
        }
    }
    else
    {
        return Widget::eventFilter(watched, event);
    }
}
